package cn.thoughtworks.school.controllers;

import cn.thoughtworks.school.annotations.Auth;
import cn.thoughtworks.school.entities.User;
import cn.thoughtworks.school.entities.Video;
import cn.thoughtworks.school.exceptions.BusinessException;
import cn.thoughtworks.school.services.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/api/videos")
public class VideoController {

  @Autowired
  private VideoService videoService;

  @PostMapping
  public ResponseEntity createVideo(@RequestBody Video video) {
    video = videoService.createVideo(video);

    return new ResponseEntity(video, HttpStatus.CREATED);
  }

  @PutMapping("{id}")
  public ResponseEntity editVideo(@PathVariable Long id,
                                  @RequestBody Video video) throws BusinessException {
    video = videoService.editVideo(id, video);

    return new ResponseEntity(video, HttpStatus.NO_CONTENT);
  }

  @GetMapping("/users/subscriptions")
  public ResponseEntity getMySubscriptionVideos(@Auth User user) {
    return ResponseEntity.ok(videoService.getMySubscriptionVideos(user.getId()));
  }
  @GetMapping("my")
  public ResponseEntity getMyVideos(@Auth User user) {
    return ResponseEntity.ok(videoService.getMyVideosByOrganization(user.getId()));
  }

  @GetMapping("pageable")
  public ResponseEntity getPageableVideos(@Auth User user,
                                          @PageableDefault(value = 12) Pageable pageable) {
    return ResponseEntity.ok(videoService.getPageableVideosByOrganization(user.getId(),pageable));
  }

  @GetMapping("top")
  public ResponseEntity getTopVideos(@Auth User user) {
    return ResponseEntity.ok(videoService.getTopVideosByOrganization(user.getId()));
  }

  @DeleteMapping("{id}")
  public ResponseEntity deleteVideo(@PathVariable Long id) throws BusinessException {
    videoService.deleteVideo(id);
    return ResponseEntity.noContent().build();
  }

  @GetMapping("{id}")
  public ResponseEntity getVideo(@PathVariable Long id,@Auth User user) throws BusinessException {
    return ResponseEntity.ok(videoService.getVideo(id,user));
  }

}
